<template>
  <div class="afterInvestDel-page">
    <pubChunk :mt="20">
      <span slot="title">收益风险指标</span>
      <div :key="list_riskIndicators_key1" class="showChunk">
        <el-table
          v-loading="listLoading_riskIndicators"
          :data="list_riskIndicators"
          fit
          default-expand-all
          row-key="rowKey"
          size="mini"
          style="width: 100%"
          :cell-class-name="cellClass"
          :cell-style="{ padding: '8px 0' }"
          :header-cell-style="{ color: '#333' }"
        >
          <el-table-column
            prop="name"
            label="名称"
            fixed="left"
            :width="flexColumnWidth('名称', 'name', list_riskIndicators)"
          >
            <template slot-scope="{ row, $index }">
              <div :title="row.name">
              <span v-if="row.hasNetWorth && !row.classifyId">
                <!-- <span
                  @click="loadChildTable(row, $index, row.treeHas)"
                  style="cursor: pointer;"
                  :class="{
                    iconfont: row.treeHas,
                    'icon-jia': row.treeHas,
                    'el-icon-minus': !row.treeHas,
                  }"
                ></span> -->
                <span
                  v-if="row.hasNetWorth && !row.classifyId"
                  @click="loadChildTable(row, $index, row.treeHas)"
                >
                  <svg
                    v-show="!row.treeHas"
                    class="icon svg-icon"
                    aria-hidden="true"
                  >
                    <use xlink:href="#icon-a-Icon-shouqi"></use>
                  </svg>
                  <svg
                    v-show="row.treeHas"
                    class="icon svg-icon"
                    aria-hidden="true"
                  >
                    <use xlink:href="#icon-Icon-zhankai"></use>
                  </svg>
                </span>
                [组合]
              </span>
              <span
                v-if="row.classifyId && !row.strategyId"
                style="margin-left: 20px"
              >
                <span v-show="row.hasNetWorth && row.classifyId">
                  <span
                    @click="loadClassifyChildTable(row, $index, row.treeHas)"
                  >
                    <svg
                      v-show="!row.treeHas"
                      class="icon svg-icon"
                      aria-hidden="true"
                    >
                      <use xlink:href="#icon-a-Icon-shouqi"></use>
                    </svg>
                    <svg
                      v-show="row.treeHas"
                      class="icon svg-icon"
                      aria-hidden="true"
                    >
                      <use xlink:href="#icon-Icon-zhankai"></use>
                    </svg>
                  </span>
                  <span
                    style="cursor: pointer; color: #1890ff; margin-right: 2px"
                  >
                    [分类]
                  </span>
                </span>
                <span
                  style="cursor: pointer; color: #1890ff"
                  @click.stop="groupDeltailHandle(row.classifyId)"
                >
                  {{ row.name }}
                </span>
              </span>
              <span
                v-else-if="row.strategyId"
                style="margin-left: 40px; cursor: pointer; color: #1890ff"
                @click.stop="strategyDeltailHandle(row)"
              >
                [投资]
                <span>{{ row.name }}</span>
              </span>
              <span v-else style="cursor: pointer; color: #666">
                {{ row.name }}
              </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="initMoney"
            label="资产金额（万元）"
            align="center"
            min-width="135"
          >
            <template slot-scope="{ row }">
              <span v-if="row.initMoney">{{ row.initMoney }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="权重" align="center">
            <template slot-scope="{ row }">
              <span v-if="row.weight">{{ row.weight | toFixed2 }}%</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="incomeRate"
            label="收益率"
            min-width="100"
            align="center"
          >
            <template slot-scope="{ row }">
              <span
                v-if="row.incomeRate"
                :class="row.incomeRate >= 0 ? 'positiveFc' : 'negativeFc'"
              >
                {{ row.incomeRate }}%
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="annualizedIncomeRate"
            label="年化收益率"
            min-width="100"
            align="center"
          >
            <template slot-scope="scope">
              <span
                v-if="scope.row.annualizedIncomeRate"
                :class="
                  scope.row.annualizedIncomeRate >= 0
                    ? 'positiveFc'
                    : 'negativeFc'
                "
              >
                {{ scope.row.annualizedIncomeRate }}%
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="annualFluctuationsRate"
            label="年化波动率"
            min-width="100"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="sharpeRate"
            label="夏普比率"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="maximumDrawdownRate"
            label="最大回撤"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="calmarRate"
            label="卡玛比率"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="maxBackIncomDay"
            label="最大回撤回补期"
            min-width="120"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.maxBackIncomDay">{{ row.maxBackIncomDay }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="maxNotByNewHightDay"
            label="最大不创新高天数"
            min-width="134"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.maxNotByNewHightDay">
                {{ row.maxNotByNewHightDay }}
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="investWinningRate"
            label="投资胜率"
            align="center"
          ></el-table-column>
        </el-table>
      </div>
    </pubChunk>
  </div>
</template>
<script>
import pubChunk from "@/components/investComn/pubChunk.vue";
import { getIndexRiskByIndexTypeAndTime } from "@/api/policyManage";
import {
  getRiskRateById,
  findClassifyByCompositionId,
  findCompositionClassifyStrategyByCompositionId,
} from "@/api/combManage";
// import debounce from 'lodash/debounce'
import { getMaxLength } from "@/utils/pro";

export default {
  components: { pubChunk },
  data() {
    return {
      list_riskIndicators_key1: 1,
      list_riskIndicators: [], // 收益风险指标
      params: {
        compositionId: "",
      },
      chart1List: [],
      nominalAmount: "",
      combTree: [],
      classfyList: [],
      combTreeStrategyList: [],
      listLoading_riskIndicators1: false,
      listLoading_riskIndicators: false,

      maxNameWidth: 100
    };
  },
  props: {
    navActive: {
      type: String | Number,
    },
    userId: {
      type: String | Number,
    },
    id: {
      type: String | Number,
      default: "",
    },
    types: {
      type: String | Number,
      default: "",
    },
    compositionName: {
      type: String | Number,
      default: "",
    },
    endTime: {
      type: String | Number,
    },
    startTime: {
      type: String | Number,
    },
    combTreeArr: {
      type: Object | Array,
    },
    contrastOptObj: {
      type: Object | Array,
    },
    combTreeStrategyListArr: {
      type: Object | Array,
    },
    indexs: {
      type: Object | Array,
    },
  },
  created() {},
  mounted() {},
  watch: {
    id: {
      handler(newVal, oldVal) {
        this.params.compositionId = newVal;
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    /**
     * 初始化收益风险指标
     * 1. 图表echart补充数据 classfyList
     * 2. 组合数据 getRiskRateByIdHandle
     * 3. 指数数据 getIndexRiskByIndexTypeAndTime
     * 4. 组合分类数据 sublistHandle
     */
    async riskTableInit(chart1List) {
      this.chart1List = chart1List;
      console.log(this.chart1List);
      this.list_riskIndicators = [];
      if (this.classfyList.length === 0) {
        await this.sublistHandle();
      }
      console.log(this.list_riskIndicators);
      this.findCompositionClassifyStrategyByCompositionId();
      // 1. 组合数据
      await this.getRiskRateByIdHandle();
      // 2. 指数数据
      await this.getIndexRiskByIndexTypeAndTime(this.indexs);
      // 3. 组合分类数据 or 投资数据
      this.loadChildTable(this.list_riskIndicators[0], 0, true);
    },
    // 组合分类收益风险数据
    async sublistHandle() {
      await findClassifyByCompositionId({
        ...this.params,
      }).then((res) => {
        this.listLoading = false;
        if (res.body.length > 1) {
          res.body.map((item, i) => {
            item.rowKey = i + 2;
            item.name = item.classfyName;
            item.compositionName = this.compositionName;
            item.weight = item.compositionWeight;
            item = Object.assign(item, item.riskIndicatorsBean);
          });
          this.classfyList = res.body;
        }
      });
    },
    // 收益风险指标
    async getRiskRateByIdHandle() {
      this.listLoading_riskIndicators1 = true;
      const res = await getRiskRateById({
        ...this.params,
        showStrategyRisk: true,
        userId: this.userId,
      });
      this.listLoading_riskIndicators1 = false;
      const row = res.body[0];
      row.name = this.compositionName;
      row.strategyId = null; // 后端给组合传回了strategyId
      row.rowKey = 1;
      row.classifyNetWorthExtendBeans =
        res.body[0].compositionNetWorthExtendBeans;
      this.list_riskIndicators = [
        { hasNetWorth: true, treeHas: false, ...row },
      ];
    },
    // 收益风险指标 指数
    async getIndexRiskByIndexTypeAndTime(indexType) {
      const res = await getIndexRiskByIndexTypeAndTime({
        indexType,
        startTime: this.startTime,
        endTime: this.endTime,
      });
      this.list_riskIndicators = this.list_riskIndicators.filter((item) => {
        return !item.indexType;
      });
      Object.keys(res.body).forEach((index) => {
        const name = this.contrastOptObj[index];
        const indexTypeList = this.list_riskIndicators.filter((item) => {
          return item.name === name;
        });
        if (indexTypeList.length === 0) {
          this.list_riskIndicators.push({
            name,
            rowKey: index + 10000,
            classifyNetWorthExtendBeans: res.body[index].scopeIndexVos,
            ...res.body[index],
          });
        }
        this.list_riskIndicators = this.flatRecursionHandle(
          this.chart1List,
          this.list_riskIndicators
        );
      });
    },
    /**
     * 不足的数据从echart图表中补充
     */
    flatRecursionHandle(resList, list) {
      list.map((items, i) => {
        const resList_i = resList.findIndex((item) => item.name == items.name);
        if (resList_i != -1) {
          const res = resList[resList_i];
          list[i] = {
            strategyId: items.strategyId,
            classifyId: items.classifyId,
            children: items.children,
            rowKey: items.rowKey,
            weight: items.weight,
            initMoney: items.initMoney,
            nominalAmount: items.nominalAmount,
            hasNetWorth: items.hasNetWorth,
            treeHas: items.treeHas,
            compositionName: items.compositionName,
            indexType: items.indexType,
            ...res,
          };
        }
      });
      return list;
    },
    loadChildTable(row, index, treeHas) {
      if (treeHas) {
        this.classfyList.forEach((item) => {
          if (this.navActive === 2) {
            item.treeHas = true;
            item.hasNetWorth = true;
          } else {
            item.treeHas = false;
            item.hasNetWorth = false;
          }
        });
        this.list_riskIndicators.splice(1, 0, ...this.classfyList);
      } else {
        this.list_riskIndicators = this.list_riskIndicators.filter((item) => {
          if (item.compositionName === row.name && item.classifyId) {
            return false;
          }
          if (item.strategyId) {
            return;
          }
          return item;
        });
      }
      row.treeHas = !treeHas;

      /**
       * 组合投资只有一个分类时会默认不展示分类
       */
      if (treeHas) {
        if (!this.classfyList.length && this.navActive === 2) {
          this.strategySublistHandle1();
        }
      } else {
        this.list_riskIndicators = this.list_riskIndicators.filter((item) => {
          if (item.classifyId === row.classifyId && item.strategyId) {
            return false;
          }
          return item;
        });
      }

      this.list_riskIndicators = this.flatRecursionHandle(
        this.chart1List,
        this.list_riskIndicators
      );
    },
    // 分类切换投资
    loadClassifyChildTable(row, index, treeHas) {
      const children = JSON.parse(JSON.stringify(this.combTree));
      const c_index = index + 1;
      if (treeHas) {
        children.forEach((item) => {
          item.classifyStrategyExt.forEach((el) => {
            el.rowKey = "C" + el.strategyId;
            el.name = el.strategyName;
            el.initMoney = el.initialMoney;
          });
          if (item.classifyId === row.classifyId) {
            this.list_riskIndicators.splice(
              c_index,
              0,
              ...item.classifyStrategyExt
            );
          }
        });
      } else {
        this.list_riskIndicators = this.list_riskIndicators.filter((item) => {
          if (item.classifyId === row.classifyId && item.strategyId) {
            return false;
          }
          return item;
        });
      }
      row.treeHas = !treeHas;
      this.list_riskIndicators = this.flatRecursionHandle(
        this.chart1List,
        this.list_riskIndicators
      );
    },
    strategySublistHandle1() {
      const new_list_riskIndicators = JSON.parse(
        JSON.stringify(this.list_riskIndicators)
      );
      const children = JSON.parse(JSON.stringify(this.combTree));
      children.forEach((item) => {
        let c_index = null;
        new_list_riskIndicators.map((citem, index) => {
          if (citem.classifyId === item.classifyId) {
            c_index = index + 1;
            citem.rowKey = "F" + item.classifyId;
            citem.name = item.classfyName;
            citem.hasNetWorth = true;
            citem.treeHas = false;
          }
        });
        item.classifyStrategyExt.forEach((el) => {
          el.rowKey = "C" + el.strategyId;
          el.name = el.strategyName;
          el.initMoney = el.initialMoney;
        });
        new_list_riskIndicators.splice(
          c_index === null ? 1 : c_index,
          0,
          ...item.classifyStrategyExt
        );
      });
      console.log(new_list_riskIndicators);
      this.list_riskIndicators = this.flatRecursionHandle(
        this.chart1List,
        new_list_riskIndicators
      );
    },
    strategyDeltailHandle(row) {
      this.$router.push({
        path: `/afterManage/investList/details/${row.strategyId}`,
      });
    },
    groupDeltailHandle(id) {
      this.$router.push({
        path: `/afterManage/investType/details/${id}`,
      });
    },
    // 组合-分类-投资树形结构
    findCompositionClassifyStrategyByCompositionId() {
      findCompositionClassifyStrategyByCompositionId({
        ...this.params,
      }).then((res) => {
        this.nominalAmount = res.body.strategyCompositionVo.nominalAmount;
        this.combTree = res.body.strategyClassifyVos;
        let list = [];
        this.combTree.forEach((item) => {
          list = list.concat(item.classifyStrategyExt);
        });
        this.combTreeStrategyList = list;
        this.$emit("update:combTreeArr", this.combTree);
        this.$emit("update:combTreeStrategyListArr", list);
        console.log("组合-分类-投资树形结构", this.combTree);
      });
    },
    /**
     * 表格数据单行显示内边距为0
     */
    cellClass(row) {
      if (
        (!row.column.label ||
          row.column.label === "名称") &&
        this.maxNameWidth < 400
      ) {
        return "cell-pad-0 nowrap";
      } else if (this.maxNameWidth >= 400) {
        return "cell-pad-0 clamp2Ellipsis";
      }
      return "";
    },
    /**
     * table column 自适应列宽
     * @param label 表名
     * @param prop 表格数据
     * @param tableData 表格数据
     */
    flexColumnWidth(label, prop, tableData) {
      const arr = tableData.map((x) => x[prop]);
      arr.push(label);
      if (getMaxLength(arr) + 80 >= 400) {
        this.maxNameWidth = 400
      }else {
        this.maxNameWidth = getMaxLength(arr) + 80
      }
      return this.maxNameWidth
    },
  },
};
</script>
<style lang="scss" scoped>
.afterInvestDel-page {
  .svg-icon {
    width: 18px;
    height: 18px;
    font-size: 18px;
    vertical-align: -0.3em;
    cursor: pointer;
  }
  .title {
    font-size: 26px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #262626;
  }
}
</style>
